<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\Erp;
use think\Db;
/**
*   同步erp中新增的用户到club 平台
*/

class Adduser extends Command
{
    
    protected function configure()
    {
        $this->setName('Adduser')->setDescription("定时同步erp中新增的用户到club平台");
    }

    protected function execute(Input $input, Output $output)
    {

        // */5 * * * *  /usr/bin/php /www/wwwroot/web/dress/think Adduser
        $output->writeln('定时命令开始执行...');

        //先获取，最大的用户注册时间
        $map['LASTTIME'] = strval(date('Ymd H:i:s', \think\Db::table('d_users')->max('create_at')));
        // $map['LASTTIME'] = $max_time;

        $erp = new Erp();
        $list = $erp->erp_add($map);
        $list_arr = json_decode($list, 1);
        $list_toarray = $list_arr['item'];
        // dd($list_toarray);

        $insertData = [];
        foreach ($list_arr['item'] as $key => $value) {
            $insertData[] = [
                'vip_number' => $value['VIPCARD'],
                'phone' => $value['MOBIL'],
                'truename' => $value['VIPNAME'],
                'level_id' => $value['VIPTYPE'],
                'gender' => $value['SEX']== 'M' ? '1' : '2',
                'user_end_time' => strtotime($value['VALIDDATE']),
                'birthday' => $value['BIRTHDAY'],
                'country' => $value['COUNTRY'],
                'city' => $value['CITY'],
                'create_at' => strtotime($value['CREATIONDATE']),
                'modify_time' => strtotime($value['MODIFIEDDATE']),
                'portrait' => $value['SEX']== 'M' ? 'default/gender1.png' : 'default/gender2.png',
                'status' => 1   
            ];
        }

        // 启动事务
        Db::startTrans();
        try{
            Db::table('d_users')->insertAll($insertData);
            // 提交事务
            Db::commit();    
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        
        $output->writeln('定时命令执行已经结束...');
    }

    /**
    *   日志
    *   content    内容
    *   status    状态：Y/N
    */
    public function add_log($content, $status)
    {
        $data = [
            'content' => $content,
            'status' => $status,
            'create_at' => time()
        ];

        $res = \think\Db::table('d_erp_syn_log')->insert($data);

        return $res;
    }
}